//
//  SHQQManager.m
//
//  Created by 索晓晓 on 2021/10/26.
//

#import "SHQQManager.h"
#import <TencentOpenAPI/TencentOpenApiUmbrellaHeader.h>

@interface SHQQManager ()
<TencentSessionDelegate>

@property (nonatomic , strong) TencentOAuth *tencentOAuth;
@property (nonatomic , strong) void (^loginComplateBlock)(NSDictionary *result);
@property (nonatomic , strong) void (^getUserComplateBlock)(NSDictionary *result);


@end

@implementation SHQQManager

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static SHQQManager *instance = nil;
    dispatch_once(&onceToken,^{
        
        NSLog(@"💠💠💠QQSDK-Version-%@",[TencentOAuth sdkVersion]);
        instance = [[SHQQManager alloc] init];
    });
    return instance;
}

+ (void)regisAppId:(NSString *)appid andUniversalLink:(NSString *)link {
    
    SHQQManager *instance = [SHQQManager sharedInstance];
    instance.tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid andUniversalLink:link andDelegate:instance];
}

/**
 @brief 处理微信url, 如果wechatSDK不能处理该url，则返回false

 @param url url
 @return 微信能处理, 返回true, 否则返回false
 */
+ (BOOL)openURL:(NSURL*)url {
    
    if ([TencentOAuth CanHandleOpenURL:url]) {
        return [TencentOAuth HandleOpenURL:url];
    }
    
    return false;
}

+ (BOOL)HandleUniversalLink:(NSURL *)url {
    if ([TencentOAuth CanHandleUniversalLink:url]) {
        
//        NSString *str = url.absoluteString;
//        str = [str stringByReplacingOccurrencesOfString:@"https://www.wwhmwin.com/qq_conn/1111996535/tencent1111996535/" withString:@"tencent1111996535://"];

//        return [TencentOAuth HandleOpenURL:[NSURL URLWithString:str]];
        return [TencentOAuth HandleUniversalLink:url];
    }
    return false;
}

+ (void)doLogin:(void(^)(NSDictionary *result))complate {
    
    NSArray* permissions = [NSArray arrayWithObjects:
                            kOPEN_PERMISSION_GET_USER_INFO,
                            kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                            kOPEN_PERMISSION_ADD_TOPIC,
                            nil];
    [SHQQManager sharedInstance].loginComplateBlock = complate;
    [[SHQQManager sharedInstance].tencentOAuth authorize:permissions];
}


/// 分享新闻到QQ
/// @param title 标题
/// @param description 描述
/// @param imageData 图片
/// @param linkUrl 跳转链接地址
/// @param qzone 是否分享到朋友圈
+ (void)shareNewsTitle:(NSString *)title
               content:(NSString *)description
       reviewImageData:(NSData *)imageData
               jumpUrl:(NSString *)linkUrl
                 qzone:(BOOL)qzone {
    
    // 分享跳转URL
    NSString *url = linkUrl;
    //分享图预览图URL地址
    QQApiNewsObject *newsObj = [QQApiNewsObject
                                objectWithURL :[NSURL URLWithString:url]
                                title: title ?:@""
                                description : description ?: @""
                                previewImageData:imageData];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
    
    if (qzone) {
        //将内容分享到qzone
        QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
        if (sent == EQQAPISENDSUCESS) {
            NSLog(@"发起分享QQ成功");
        } else {
            NSLog(@"发起分享QQ失败%ld",sent);
        }
    } else {
        //将内容分享到qq
        QQApiSendResultCode sent = [QQApiInterface sendReq:req];
        if (sent == EQQAPISENDSUCESS) {
            NSLog(@"发起分享QQ成功");
        } else {
            NSLog(@"发起分享QQ失败%ld",sent);
        }
    }
}

/// 分享纯图片到QQ
/// @param imageData 图片二进制数据
/// @param title 标题
/// @param description 描述
+ (void)shareImgae:(NSData *)imageData
             title:(NSString *)title
           content:(NSString *)description {
    
    //开发者分享图片数据
    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:imageData
                                               previewImageData:imageData
                                               title:@"title"
                                               description :@"description"];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:imgObj];
    //将内容分享到
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    if (sent == EQQAPISENDSUCESS) {
        NSLog(@"发起分享QQ成功");
    } else {
        NSLog(@"发起分享QQ失败%ld",sent);
    }
}


/// 分享纯文本到QQ
/// @param title 标题
+ (void)shareTitle:(NSString *)title {
    
    //开发者分享的文本内容
    QQApiTextObject *txtObj = [QQApiTextObject objectWithText:title];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:txtObj];
    //将内容分享到
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    if (sent == EQQAPISENDSUCESS) {
        NSLog(@"发起分享QQ成功");
    } else {
        NSLog(@"发起分享QQ失败%ld",sent);
    }
}

#pragma mark - 登录回调
- (void)tencentDidLogin
{
    
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length]){
        
        [result setObject:_tencentOAuth.accessToken forKey:@"accessToken"];
        [result setObject:_tencentOAuth.openId forKey:@"openId"];
        [result setObject:_tencentOAuth.openId forKey:@"openId"];
        [result setObject:@"登录成功" forKey:@"message"];
        [result setObject:@(true) forKey:@"isSuccess"];
        
    } else {
        
        [result setObject:@"登录不成功 没有获取accesstoken" forKey:@"message"];
        [result setObject:@(false) forKey:@"isSuccess"];
    }
    
    if([SHQQManager sharedInstance].loginComplateBlock){
        [SHQQManager sharedInstance].loginComplateBlock(result);
        [SHQQManager sharedInstance].loginComplateBlock = nil;
    }
}

- (void)tencentDidNotLogin:(BOOL)cancelled {
    
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    
    [result setObject:@(false) forKey:@"isSuccess"];

    if (cancelled) {
        [result setObject:@"用户取消登录" forKey:@"message"];
    } else {
        [result setObject:@"登录失败" forKey:@"message"];
    }
    
    if([SHQQManager sharedInstance].loginComplateBlock){
        [SHQQManager sharedInstance].loginComplateBlock(result);
        [SHQQManager sharedInstance].loginComplateBlock = nil;
    }
}

- (void)tencentDidNotNetWork {
//    _labelTitle.text=@"无网络连接，请设置网络";
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    
    [result setObject:@(false) forKey:@"isSuccess"];
    [result setObject:@"无网络连接，请设置网络" forKey:@"message"];

    if([SHQQManager sharedInstance].loginComplateBlock){
        [SHQQManager sharedInstance].loginComplateBlock(result);
        [SHQQManager sharedInstance].loginComplateBlock = nil;
    }
}

+ (void)getQQUserInfo:(void(^)(NSDictionary *result))complate {
    
    if ([SHQQManager sharedInstance].tencentOAuth.accessToken && 0 != [[SHQQManager sharedInstance].tencentOAuth.accessToken length]){
        [SHQQManager sharedInstance].getUserComplateBlock = complate;
        [[[SHQQManager sharedInstance] tencentOAuth] getUserInfo];
        return;
    }
    
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    [result setObject:@(false) forKey:@"isSuccess"];
    [result setObject:@"用户没有登录" forKey:@"message"];
    if (complate){
        complate(result);
    }
}

/**
 * 获取用户个人信息回调
 * \param response API返回结果，具体定义参见sdkdef.h文件中\ref APIResponse
 * \remarks 正确返回示例: \snippet example/getUserInfoResponse.exp success
 *          错误返回示例: \snippet example/getUserInfoResponse.exp fail
 */
- (void)getUserInfoResponse:(APIResponse*) response {
    
    if(self.getUserComplateBlock){
        
        NSLog(@"%@",response);
//    info:{
//        city = "\U8679\U53e3";
//        constellation = "";
//        figureurl = "http://qzapp.qlogo.cn/qzapp/1111996535/B5F235E2AB952DF4C6B8A2B033058B99/30";
//        "figureurl_1" = "http://qzapp.qlogo.cn/qzapp/1111996535/B5F235E2AB952DF4C6B8A2B033058B99/50";
//        "figureurl_2" = "http://qzapp.qlogo.cn/qzapp/1111996535/B5F235E2AB952DF4C6B8A2B033058B99/100";
//        "figureurl_qq" = "http://thirdqq.qlogo.cn/g?b=oidb&k=gIGjtfS6WIW42gtFTZicMUg&s=640&t=1557160331";
//        "figureurl_qq_1" = "http://thirdqq.qlogo.cn/g?b=oidb&k=gIGjtfS6WIW42gtFTZicMUg&s=40&t=1557160331";
//        "figureurl_qq_2" = "http://thirdqq.qlogo.cn/g?b=oidb&k=gIGjtfS6WIW42gtFTZicMUg&s=100&t=1557160331";
//        "figureurl_type" = 1;
//        gender = "\U7537";
//        "gender_type" = 2;
//        "is_lost" = 0;
//        "is_yellow_vip" = 0;
//        "is_yellow_year_vip" = 0;
//        level = 0;
//        msg = "";
//        nickname = "\U6e21\U53e3\U4e36\U84dd\U8349";
//        province = "\U4e0a\U6d77";
//        ret = 0;
//        vip = 0;
//        year = 1991;
//        "yellow_vip_level" = 0;
//    }
        NSDictionary *jsonResponse = response.jsonResponse;
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        if (response.retCode == URLREQUEST_SUCCEED) {
            [param setObject:self.tencentOAuth.openId forKey:@"openid"];
            [param setObject:jsonResponse[@"nickname"]?:@"" forKey:@"nickname"];
            [param setObject:jsonResponse[@"figureurl"]?:@"" forKey:@"figureurl"];
            [param setObject:jsonResponse[@"gender_type"]?:@"0" forKey:@"gender_type"];
            [param setObject:@(true) forKey:@"isSuccess"];
            self.getUserComplateBlock(param);
            self.getUserComplateBlock = nil;
        } else {
            [param setObject:@(false) forKey:@"isSuccess"];
            [param setObject:response.errorMsg?:@"登录失败" forKey:@"message"];
            self.getUserComplateBlock(param);
            self.getUserComplateBlock = nil;
        }
        
    }
    
}


@end
